package com.xuecheng.content.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.TeachplanDto;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.TeachplanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import rx.internal.operators.BackpressureUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-30
 */
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {



    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private CourseBaseService courseBaseService;


    // 查询课程计划
    @Override
    public ResponseResult treeNodes(Long courseId) {
     // 根据课程id 查询数据
        List<TeachplanVo> teachplanVos = teachplanMapper.treeNodes(courseId);
        //  筛选出一级大纲
        TeachplanVo one=null;
        for (TeachplanVo teachplanVo : teachplanVos) {
            if (teachplanVo.getGrade()==1) { // 层级为1的就是 一级大纲
                one=teachplanVo;
                break;
            }
        }
        // 筛选二级大纲
        ArrayList<TeachplanVo> two = new ArrayList<>();
        for (TeachplanVo teachplanVo : teachplanVos) {
            if (teachplanVo.getParentid().equals(one.getId())){
                two.add(teachplanVo);
            }
        }
        // 在把二级关联到一级
        one.setTeachPlanTreeNodes(two);

        if (CollectionUtil.isNotEmpty(two)){
            // 筛选三级小节
            for (TeachplanVo two2 : two) {
                // 获取二级id
                Long towid = two2.getId();
                // 声明三级list
                ArrayList<TeachplanVo> three = new ArrayList<>();
                for (TeachplanVo teachplanVo : teachplanVos) {
                    if (teachplanVo.getParentid().equals(towid)) {
                        three.add(teachplanVo);
                    }
                }
               two2.setTeachPlanTreeNodes(three);
            }

        }



    return ResponseResult.okResult(one);
    }
    // 保存或者修改课程计划
    @Override
    public ResponseResult updateTeachplan(TeachplanDto dto) {
      // 查询课程信息
        CourseBase courseBase = courseBaseService.getById(dto.getCourseId());
        // 判断课程的状态
        String auditStatus = courseBase.getAuditStatus();
        if (StrUtil.equals(auditStatus, CourseConstants.AUDIT_COMMIT_STATUS)||
                StrUtil.equals(auditStatus, CourseConstants.AUDIT_PASTED_STATUS)||
                StrUtil.equals(auditStatus, CourseConstants.AUDIT_PUBLISHED_STATUS)){
            throw  new BusinessException(ErrorCode.UPDATEEERROR);
        }
        // 转型
        Teachplan teachplan = BeanHelper.copyProperties(dto, Teachplan.class);
        // 二级章节
        if (teachplan.getGrade()==2){
            //查询一级大纲
            LambdaQueryWrapper<Teachplan> qw = new LambdaQueryWrapper<>();
            qw.eq(Teachplan::getCourseId,teachplan.getCourseId());
            qw.eq(Teachplan::getGrade,1);
            Teachplan t = this.getOne(qw);
            teachplan.setParentid(t.getId());
        }
        // 添加三级小节
        if (teachplan.getId()==null && teachplan.getGrade()==3){
            courseBase.setPlanNum(courseBase.getPlanNum()+1);
            courseBaseService.updateById(courseBase);
        }
        // 新增或者修改
        this.saveOrUpdate(teachplan);
        // 返回结果
        return ResponseResult.okResult();


    }
    // 删除课程计划
    @Override
    public ResponseResult deleteTeachPlan(Long id) {
        // 根据课程id查询数据库
        Teachplan teachplan = this.getById(id);
        //  查询课程信息
        CourseBase courseBase = courseBaseService.getById(teachplan.getCourseId());
        // 判断课程的信息
        String status = courseBase.getAuditStatus(); // 先看他是什么状态
        if (StrUtil.equals(status,CourseConstants.AUDIT_COMMIT_STATUS)||
                StrUtil.equals(status,CourseConstants.AUDIT_PASTED_STATUS)||
                StrUtil.equals(status,CourseConstants.AUDIT_PUBLISHED_STATUS)){
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        };
        // 判断计划的级别
        if (teachplan.getGrade()==2){ // 如果他是二级
            LambdaQueryWrapper<Teachplan> qw = new LambdaQueryWrapper<>();
            qw.eq(Teachplan::getParentid,teachplan.getId());
            long count = this.count(qw);
            if (count>0){ // 并且有三级的数据 是不能删除的
                throw new BusinessException(ErrorCode.UPDATEEERROR);
            }
            this.removeById(id);
        } else { // 三级的话
            //先是章节数减去1  在更新
            courseBase.setPlanNum(courseBase.getPlanNum()-1);
            courseBaseService.updateById(courseBase);

            this.removeById(id);
        }

        return ResponseResult.okResult();
    }
    // 查询课程计划
    @Override
    public ResponseResult treeNodes2(Long courseId) {
     // 根据课程id 查询数据
        List<TeachplanVo> voList = teachplanMapper.treeNodes(courseId);
        // 筛选一级大纲
        TeachplanVo one = voList.stream().filter(teachplanVo -> teachplanVo.getGrade() == 1).findFirst().get();
        // 筛选二级章节
        List<TeachplanVo> twoList = voList.stream().filter(teachplanVo -> teachplanVo.getParentid().equals(one.getId())).collect(Collectors.toList());
        //将二级关联到一级
        one.setTeachPlanTreeNodes(twoList);
        //筛选三级小节
        if (CollectionUtil.isNotEmpty(twoList)){
            for (TeachplanVo teachplanVo : twoList) {
                // 获取二级id
                Long twoid = teachplanVo.getId();
                List<TeachplanVo> threeList = voList.stream().filter(teachplanVo1 -> teachplanVo.getParentid().equals(twoid)).collect(Collectors.toList());
                //将三级关联到二级
                teachplanVo.setTeachPlanTreeNodes(threeList);
            }
        }
        return ResponseResult.okResult(one);
    }
}
